<template>
  <div class="htx-color">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>RGB 转换成 HEX</span>
        <div class="color-box" :style="{ background: hexInput1 }"></div>
      </div>
      <el-row class="row-rgb">
        <el-col :span="10">
          <el-input v-model="rgbInput1" placeholder="如：rgb(0, 0, 0) 或 0, 0, 0">
            <template slot="prepend">RGB</template>
          </el-input>
        </el-col>
        <el-col :span="4">
          <div class="button-wrap">
            <el-button type="primary" icon="el-icon-sort" circle @click="handleR2H"></el-button>
          </div>
        </el-col>
        <el-col :span="10">
          <el-input v-model="hexInput1">
            <template slot="prepend">HEX</template>
          </el-input>
        </el-col>
      </el-row>
    </el-card>

    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>HEX 转换成 RGB</span>
        <div class="color-box" :style="{ background: rgbInput2 }"></div>
      </div>
      <el-row class="row-hex">
        <el-col :span="10">
          <el-input v-model="hexInput2" placeholder="如：#fff 或 #ffffff">
            <template slot="prepend">HEX</template>
          </el-input>
        </el-col>
        <el-col :span="4">
          <div class="button-wrap">
            <el-button type="primary" icon="el-icon-sort" circle @click="handleH2R"></el-button>
          </div>
        </el-col>
        <el-col :span="10">
          <el-input v-model="rgbInput2">
            <template slot="prepend">RGB</template>
          </el-input>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script>
import { rgbToHex, hexToRgb } from '@/lib/color';

export default {
  data() {
    return {
      rgbInput1: '',
      rgbInput2: '',
      hexInput1: '',
      hexInput2: '',
    };
  },
  methods: {
    handleR2H() {
      let formatRgb = [];
      try {
        if (this.rgbInput1.indexOf('rgb') < 0) {
          const tempArr = this.rgbInput1.split(',');
          if (tempArr.length === 3) {
            formatRgb = tempArr.map((item) => Number(item));
          }
        } else {
          formatRgb = /(.+)?(?:\(|（)(.+)(?=\)|）)/.exec(this.rgbInput1)[2].split(',');
        }
      } catch (e) {
        this.showError();
        return false;
      }
      if (formatRgb.length !== 3) {
        this.showError();
        return false;
      }
      const rgbList = [];
      formatRgb.forEach((item) => {
        rgbList.push(Number(item));
      });
      this.hexInput1 = rgbToHex(...rgbList);
      return true;
    },
    handleH2R() {
      try {
        this.rgbInput2 = `rgb(${hexToRgb(this.hexInput2).join(',')})`;
      } catch (e) {
        this.showError();
      }
    },
    showError() {
      this.$notify.error({
        title: '格式错误',
        message: '请重新输入',
      });
    },
  },
};
</script>
